package com.aptech.restrant.Controller;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aptech.restrant.Bean.FoodDataBean;
import com.aptech.restrant.Model.FoodBean;
import com.aptech.restrant.Model.PageBean;


public class SelectPage extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		response.setContentType("text/html;charset=GBK");
		
		//获取餐品列表
		FoodDataBean gdb = new FoodDataBean();
		
		//分页开始
		int num = 8;//每页显示多少条记录
		int count = gdb.getCount();
		int loadPage = 1;
		int backPage = 1;
		int nextPage = 1;
		int maxPage = 1;
		if(backPage<=1){
			backPage = 1;
		}
		if(count%num==0){
			maxPage = count/num;
		}else{
			maxPage = (count/num)+1;
		}
		if(request.getParameter("page")!=null){
			try{
				loadPage = Integer.parseInt(request.getParameter("page"));
			}catch(NumberFormatException e){
				loadPage = 1;
			}finally{
				if(loadPage>maxPage)loadPage = maxPage;
				if(loadPage<1)loadPage = 1;
			}
		}else{
			loadPage = 1;
		}
		
		int pageCount = num*(loadPage-1);
		//分页结束
		PageBean pageBean = new PageBean(num,count,loadPage,backPage,nextPage,maxPage,pageCount);
		
		List<FoodBean> foods = gdb.getPageFoods(loadPage,num);
		
		session.setAttribute("foods", foods);
		session.setAttribute("page", pageBean);

		RequestDispatcher dispatcher = request.getRequestDispatcher("show.jsp");
		
		dispatcher.forward(request, response);
		
	}

}
